package com.aaa.springsecurity04.service;

import com.aaa.springsecurity04.dao.PermissionDao;
import com.aaa.springsecurity04.dao.UserDao;
import com.aaa.springsecurity04.entity.Permission;
import com.aaa.springsecurity04.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service //交于spring容器管理
public class MyUserService implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users=userDao.selectByUsername(username);
        if(users!=null){
            //该用户具有的对应权限
            Collection<GrantedAuthority> authorities=new ArrayList();
            //根据用户id查询用户具有的权限
            List<Permission>permissions=permissionDao.findByUserId(users.getUserid());

            //把上面的权限封装authorities中
            authorities=permissions.stream()
                    .map(item->new SimpleGrantedAuthority(item.getPercode()))
                    .collect(Collectors.toList());
            //跟上边一样↑上叫stream流
//            for (Permission item:permissions){
//                SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(item.getPercode());
//                authorities.add(simpleGrantedAuthority);
//            }

            User user=new User(username, users.getUserpwd(),authorities );
            return user;
        }
        return null;


    }
}
